<?php
/**
 * 云存储
 *
 */
require_once dirname(__FILE__).'/sdk.class.php';

class OSS {
	
	protected $service;
	protected $bucket;
	protected $objectPath;
	
	public function __construct () {
		try {
			$this->service = new ALIOSS();
			$this->service->set_debug_mode(false);
//			$this->service->set_enable_domain_style(true); // 设置开启三级域名
			return $this;
		} catch (Exception $e) {
			trigger_error(print_r($e->getMessage(), true), E_USER_WARNING);
			return false;
		}
	}
	
	/**
	 * 设置bucket
	 * @param string $bucket
	 * @return AliOSS
	 */
	public function setBucket ($bucket) {
		$this->bucket = $bucket;
		return $this;
	}
	
	/**
	 * 设置object存放目录
	 * @param string $path
	 * @return OSS
	 */
	public function setObjectPath ($path) {
		$this->objectPath = $path;
		return $this;
	}
	
	/**
	 * 通过内容上传文件
	 * @param string $object
	 * @param string $content
	 * @return boolean false | array $rs
	 */
	public function uploadByContent ($object, $content) {
		$expires = date('Y-m-d H:i:s', strtotime('+10years'));
		$len = strlen($content);
		$upload_file_options = array(
			'content' => $content,
			'length' => $len,
			ALIOSS::OSS_HEADERS => array(
				'Expires' => $expires,
			),
		);
		try {
			$rs = $this->service->upload_file_by_content($this->bucket, $this->objectPath.$object, $upload_file_options);
			if (!$rs->isOk()) {
				trigger_error('OSS error: '.print_r($rs, true), E_USER_WARNING);
				return false;
			}
			$rs_len = $rs->header['_info']['upload_content_length'];
			if ($len != $rs_len) return false;
			return array(
				'etag' => str_replace('"', '', $rs->header['etag']),
				'url' => $rs->header['_info']['url'],
				'content_length' => $rs_len,
			);
		} catch (Exception $e) {
			trigger_error('OSS error: '.print_r($e->getMessage(), true), E_USER_WARNING);
			return false;
		}
	}
	
	/**
	 * 通过内容上传文件
	 * @param string $object
	 * @param string $file_path
	 * @return boolean false | array $rs
	 */
	public function uploadByFile ($object, $file_path) {
		try {
			$rs = $this->service->upload_file_by_file($this->bucket, $this->objectPath.$object, $file_path);
			if (!$rs->isOk()) {
				trigger_error('OSS error: '.print_r($rs, true), E_USER_WARNING);
				return false;
			}
			$rs_len = $rs->header['_info']['upload_content_length'];
			if (filesize($file_path) != $rs_len) return false;
			return array(
				'etag' => str_replace('"', '', $rs->header['etag']),
				'url' => $rs->header['_info']['url'],
				'content_length' => $rs_len,
			);
		} catch (Exception $e) {
			trigger_error('OSS error: '.print_r($e->getMessage(), true), E_USER_WARNING);
			return false;
		}
	}
	
	public function getObject($object){
		return $this->service->get_object($this->bucket, $this->objectPath.$object);
	}
}
